<template>
  <div class="log-search">
    <h1 class="page-title">日志检索</h1>
    
    <!-- 检索表单 -->
    <div class="card search-form-card">
      <el-form :model="searchForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="时间范围">
              <el-date-picker
                v-model="searchForm.timeRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                style="width: 100%"
                :shortcuts="timeShortcuts"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="日志级别">
              <el-select v-model="searchForm.logLevel" placeholder="全部" clearable style="width: 100%">
                <el-option label="DEBUG" value="DEBUG" />
                <el-option label="INFO" value="INFO" />
                <el-option label="WARN" value="WARN" />
                <el-option label="ERROR" value="ERROR" />
                <el-option label="FATAL" value="FATAL" />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="系统类型">
              <el-select v-model="searchForm.systemType" placeholder="全部" clearable style="width: 100%">
                <el-option label="web-server" value="web-server" />
                <el-option label="test-service" value="TEST-SERVICE" />
                <el-option label="data-service" value="data-service" />
                <el-option label="nginx" value="nginx" />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="关键字">
              <el-input v-model="searchForm.keyword" placeholder="请输入关键字" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="24" style="text-align: right">
            <el-button @click="resetForm">重置</el-button>
            <el-button type="primary" :loading="loading" @click="handleSearch">
              <el-icon><Search /></el-icon> 检索
            </el-button>
            <el-button type="success" @click="handleExport">
              <el-icon><Download /></el-icon> 导出
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    
    <!-- 检索结果 -->
    <div class="card">
      <div class="result-header" v-if="!loading || (tableData && tableData.length > 0)">
        <div>
          <span class="result-count">共找到 {{ total || 0 }} 条日志</span>
          <el-tag v-if="cacheHit" type="success" size="small" style="margin-left: 10px">
            <el-icon><CircleCheck /></el-icon> 缓存命中
          </el-tag>
        </div>
      </div>
      
      <el-table
        :data="tableData"
        stripe
        style="width: 100%"
        v-loading="loading"
        @row-click="handleRowClick"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="logLevel" label="级别" width="100">
          <template #default="scope">
            <el-tag :type="getLevelType(scope.row.logLevel)" size="small">
              {{ scope.row.logLevel }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="systemType" label="系统" width="150" />
        <el-table-column prop="timestamp" label="时间" width="180" />
        <el-table-column prop="content" label="日志内容" show-overflow-tooltip />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click.stop="viewDetail(scope.row)">
              <el-icon><View /></el-icon> 详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 空状态 -->
      <el-empty
        v-if="!loading && (!tableData || tableData.length === 0)"
        description="暂无日志数据"
        :image-size="100"
      >
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>
          重新搜索
        </el-button>
      </el-empty>
      
      <!-- 分页组件 -->
      <div class="pagination" v-if="tableData && tableData.length > 0">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @size-change="handleSearch"
          @current-change="handleSearch"
        />
      </div>
    </div>
    
    <!-- 日志详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      title="日志详情"
      width="800px"
      destroy-on-close
    >
      <div v-if="currentLog" class="log-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="日志ID">{{ currentLog.id }}</el-descriptions-item>
          <el-descriptions-item label="日志级别">
            <el-tag :type="getLevelType(currentLog.logLevel)">
              {{ currentLog.logLevel }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="系统类型">{{ currentLog.systemType }}</el-descriptions-item>
          <el-descriptions-item label="时间戳">{{ currentLog.timestamp }}</el-descriptions-item>
          <el-descriptions-item label="采集源ID">{{ currentLog.sourceId }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentLog.createTime }}</el-descriptions-item>
          <el-descriptions-item label="原始内容" :span="2">
            <div class="log-content">{{ currentLog.content }}</div>
          </el-descriptions-item>
        </el-descriptions>
        
        <div v-if="currentLog.fields" class="fields-section">
          <h4>结构化字段</h4>
          <el-tag v-for="(value, key) in currentLog.fields" :key="key" style="margin: 5px">
            {{ key }}: {{ value }}
          </el-tag>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { queryLogs, getLogDetail } from '@/api/log'
import { ElMessage } from 'element-plus'
import { Search, Download, View, CircleCheck } from '@element-plus/icons-vue'

const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const cacheHit = ref(false)
const detailVisible = ref(false)
const currentLog = ref(null)

const searchForm = reactive({
  timeRange: [],
  logLevel: '',
  systemType: '',
  keyword: ''
})

const pagination = reactive({
  current: 1,
  pageSize: 20
})

// 时间快捷选项
const timeShortcuts = [
  {
    text: '最近1小时',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000)
      return [start, end]
    }
  },
  {
    text: '最近6小时',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 6)
      return [start, end]
    }
  },
  {
    text: '最近24小时',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24)
      return [start, end]
    }
  },
  {
    text: '最近7天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  }
]

// 检索日志
const handleSearch = async () => {
  loading.value = true
  
  const params = {
    startTime: searchForm.timeRange[0] || null,
    endTime: searchForm.timeRange[1] || null,
    logLevel: searchForm.logLevel || null,
    systemType: searchForm.systemType || null,
    keyword: searchForm.keyword || null,
    pageNum: pagination.current,
    pageSize: pagination.pageSize
  }
  
  try {
    const res = await queryLogs(params)
    console.log('API响应数据:', res) // 调试日志
    
    if (res.code === 200 && res.data) {
      // 后端返回的字段是 list，不是 records
      tableData.value = res.data.list || res.data.records || []
      total.value = res.data.total || 0
      cacheHit.value = res.data.cacheHit || false
      
      console.log('解析后的数据:', {
        tableData: tableData.value.length,
        total: total.value
      })
    } else {
      // 如果没有数据，设置为空数组
      tableData.value = []
      total.value = 0
      cacheHit.value = false
      
      if (res.message) {
        ElMessage.warning(res.message)
      }
    }
  } catch (error) {
    console.error('检索失败:', error)
    ElMessage.error('检索失败')
    // 出错时也要确保 tableData 是数组
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetForm = () => {
  searchForm.timeRange = []
  searchForm.logLevel = ''
  searchForm.systemType = ''
  searchForm.keyword = ''
  pagination.current = 1
  handleSearch()
}

// 查看详情
const viewDetail = async (row) => {
  try {
    const res = await getLogDetail(row.id)
    if (res.code === 200) {
      currentLog.value = res.data
      detailVisible.value = true
    }
  } catch (error) {
    ElMessage.error('获取详情失败')
  }
}

// 行点击
const handleRowClick = (row) => {
  viewDetail(row)
}

// 导出
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 获取级别类型
const getLevelType = (level) => {
  const typeMap = {
    'DEBUG': 'info',
    'INFO': 'success',
    'WARN': 'warning',
    'ERROR': 'danger',
    'FATAL': 'danger'
  }
  return typeMap[level] || 'info'
}

// 页面加载时自动搜索
onMounted(() => {
  handleSearch()
})
</script>

<style scoped lang="scss">
.log-search {
  .search-form-card {
    margin-bottom: 20px;
  }
  
  .result-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .result-count {
      font-size: 14px;
      color: var(--text-secondary);
    }
  }
  
  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .log-detail {
    .log-content {
      white-space: pre-wrap;
      word-break: break-all;
      background-color: var(--el-fill-color-light);
      padding: 12px;
      border-radius: 4px;
      font-family: 'Courier New', monospace;
      font-size: 13px;
      line-height: 1.6;
    }
    
    .fields-section {
      margin-top: 20px;
      
      h4 {
        margin-bottom: 12px;
        color: var(--text-primary);
      }
    }
  }
}
</style>

